package com.mahjong.server.manager;

import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

import org.apache.mina.core.session.IoSession;
import org.springframework.stereotype.Component;

import com.mahjong.server.model.Player;

/**
 * 在线管理
 * 
 * @author Simple
 * @date 2013-4-2 上午10:59:07
 * @Description TODO
 */
@Component
public class OnlineManager {

  // 在线玩家列表
  public Queue<Player> onlinePlayers=new ConcurrentLinkedQueue<Player>();

  // 用户名-玩家映射
  public Map<String, Player> username2player=new ConcurrentHashMap<String, Player>();

  /**
   * 把玩家设置为在线
   * 
   * @param player
   */
  public void addOnline(Player player) {
    this.onlinePlayers.add(player);
    this.username2player.put(player.getUser().getUsername(), player);
  }

  /**
   * 通过玩家ID获得玩家对象
   * 
   * @param id
   * @return
   */
  public Player getPlayerById(int id) {
    for(Player p: this.onlinePlayers) {
      if(p.getId() == id) {
        return p;
      }
    }
    return null;
  }

  /**
   * 通过username获得玩家对象
   * 
   * @param username
   * @return
   */
  public Player getPlayerByName(String username) {
    return this.username2player.get(username);
  }

  /**
   * 获得所有在线玩家
   * 
   * @return
   */
  public Queue<Player> getAllOnlinePlayer() {
    return this.onlinePlayers;
  }

  /**
   * 从在线列表中移除该玩家
   * 
   * @param player
   */
  public void removeOnline(Player player) {
    this.onlinePlayers.remove(player);
    this.username2player.remove(player.getUser().getUsername());
  }

  /**
   * 从在线列表中移除该玩家
   * 
   * @param session
   */
  public void removeOnline(IoSession session) {
    Player player=this.getPlayerBySession(session);
    removeOnline(player);
  }

  /**
   * 通过session获得玩家对象
   * 
   * @param session
   * @return
   */
  public Player getPlayerBySession(IoSession session) {
    for(Player p: onlinePlayers) {
      if(p.getSession().getId() == session.getId()) {
        return p;
      }
    }
    return null;
  }
}
